using UnityEngine;
using UnityEngine.UI;

public class UiHpBar : MonoBehaviour
{
    private Entity entity => GetComponentInParent<Entity>();
    private RectTransform rectTransform => GetComponent<RectTransform>();
    private Slider slider => GetComponentInChildren<Slider>();
    private CharacterStats stats => GetComponentInParent<CharacterStats>();

    private void Awake()
    {
        GetComponent<Canvas>().worldCamera = Camera.main;
    }

    private void OnEnable()
    {
        entity.OnFlipped += FlipUi;
        stats.OnHpChanged += UpdateHpUi;
    }

    private void Start()
    {
        UpdateHpUi(stats.GetMaxHp(), stats.CurrentHp);
    }

    private void OnDisable()
    {
        if (entity)
            entity.OnFlipped -= FlipUi;
        if (stats)
            stats.OnHpChanged -= UpdateHpUi;
    }

    private void UpdateHpUi(int maxHp, int currentHp)
    {
        slider.maxValue = maxHp;
        slider.value = currentHp;
    }

    private void FlipUi()
    {
        rectTransform.Rotate(0, 180, 0);
    }
}
